﻿
namespace Aeon.Emulator.Instructions.FPU
{
    internal static class Fcom
    {
        [Opcode("D8/2 mf32", OperandSize = 16 | 32, AddressSize = 16 | 32)]
        public static void Compare32(VirtualMachine vm, float value)
        {
            Compare64(vm, value);
        }

        [Opcode("DC/2 mf64|D8D0+ st", OperandSize = 16 | 32, AddressSize = 16 | 32)]
        public static void Compare64(VirtualMachine vm, double value)
        {
            vm.Processor.FPU.StatusFlags &= ~ConditionCodes.ConditionMask;
            FPUStatus status = FPUStatus.Clear;

            double st0 = vm.Processor.FPU.ST0;

            if(st0 > value)
                status = ConditionCodes.GreaterThan;
            else if(st0 < value)
                status = ConditionCodes.LessThan;
            else if(st0 == value)
                status = ConditionCodes.Zero;
            else
            {
                status = ConditionCodes.Unordered;
                vm.Processor.FPU.StatusFlags |= FPUStatus.InvalidOperation;
            }

            vm.Processor.FPU.StatusFlags |= status;
        }
    }

    internal static class Fcomp
    {
        [Opcode("D8/3 mf32", OperandSize = 16 | 32, AddressSize = 16 | 32)]
        public static void ComparePop32(VirtualMachine vm, float value)
        {
            Fcom.Compare32(vm, value);
            vm.Processor.FPU.Pop();
        }

        [Opcode("DC/3 mf64|D8D8+ st", OperandSize = 16 | 32, AddressSize = 16 | 32)]
        public static void ComparePop64(VirtualMachine vm, double value)
        {
            Fcom.Compare64(vm, value);
            vm.Processor.FPU.Pop();
        }
    }

    internal static class Fcompp
    {
        [Opcode("DED9", OperandSize = 16 | 32, AddressSize = 16 | 32)]
        public static void CompareDoublePop64(VirtualMachine vm)
        {
            Fcom.Compare64(vm, vm.Processor.FPU.GetRegisterValue(1));
            vm.Processor.FPU.Pop();
            vm.Processor.FPU.Pop();
        }
    }
}
